// pages/order_tj/order_tj.js
var app = getApp();
var utils = require('../../utils/util.js');
var area = require('../../utils/lib/area.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {

      back_address_id: 0,
      Gift_ID: 0,//产品
      info: {},//信息
      //收货地址信息
      address_info: {
        Address_ID: 0,
        Address_Name: '',
        Address_Mobile: '',
        Address_Province: '',   //名称
        Address_City: '',       //名称
        Address_Area: '',       //名称
        Address_Detailed: ''
      },

      //JSON 字符串
      json: {
        username:'',
        mobile: '',
        address: '',
        remark: '',
      },
      pay_flag: false,
      payText: "提交订单",
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading({
      title: '加载中',
    });
    this.setData({
      Gift_ID: options.Gift_ID
    })
    if (!app.globalData.userInfo) {
      app.login('', this.load);
    } else {
      this.load();
    }
  },
  //页面加载
  load: function () {
    wx.hideLoading()
    //获取收货地址
    var addressArgs = {
      User_ID: app.globalData.userInfo.User_ID,
      act: 'get_address',
    };
    if (this.data.back_address_id) {  //添加、选择收获地址返回
      addressArgs.Address_ID = this.data.back_address_id;
    } else if (this.data.address_info.Address_ID) { //有收获地址，则更新（防止收获地址编辑后返回）
      addressArgs.Address_ID = this.data.address_info.Address_ID;
    }
    app.http_req(addressArgs, app.globalData.init.api_url, 'POST', this.getAddress);

    //获取产品信息
    var transData = {
      Gift_ID: this.data.Gift_ID,
      act: 'jifen_pro_detail'
    };
    app.http_req(transData, app.globalData.init.api_url, 'POST', this.prod_detail);
  },

  /**
   * 产品信息
   */
  prod_detail: function (res) {
    if (res.errorCode == 0) {
      res.data.Gift_ImgPath = app.globalData.init.front_url + res.data.Gift_ImgPath
      /**
       * 判断收发货方式，是否支持到店自提
       * 默认显示选中快递，
       */
      var tab_switch = this.data.tab_switch;
      this.setData({
        info: res.data,
      });      
    } 
  },
  /**
     * 城市 信息
     */
  city_detail: function (res) {
    if (res.errorCode == 0) {
      this.setData({
        cityinfocity: res.data
      })
    }
  },

  //收货地址跳转
  address: function (e) {
    //判断是添加还是选择
    var address_id = e.currentTarget.dataset.addressid;
    wx.navigateTo({
      url: address_id ? '../addresslist/addresslist?from=checkout&addressid=' + address_id : '../addressaddedit/addressaddedit?from=checkout'
    });
  },

  //获取收货地址
  getAddress: function () {
    var addressArgs = {
      act: 'get_address',
      User_ID: app.globalData.userInfo.User_ID
    };
    if (this.data.back_address_id) {  //添加、选择收获地址返回
      addressArgs.Address_ID = this.data.back_address_id;
    } else if (this.data.address_info.Address_ID) { //有收获地址，则更新（防止收获地址编辑后返回）
      addressArgs.Address_ID = this.data.address_info.Address_ID;
    }
    app.http_req(addressArgs, app.globalData.init.api_url, 'POST', this.getAddress_callback);
  },

  //获取收货地址回调
  getAddress: function (res) {
    wx.hideLoading();
    if (this.data.back_address_id && res.errorCode != 0) {  //添加、选择收获地址返回
      wx.showModal({
        title: '错误',
        content: '收获地址获取失败',
        showCancel: false
      });
      return false;
    }
    if (res.errorCode === 0) {
      var addresslist = res.data;
      if (typeof addresslist != 'undefined' && addresslist.length > 0) {  //有收货地址
        var addressInfo = '';
        if (this.data.back_address_id) {  //添加、选择收获地址返回
          addressInfo = addresslist[0];
        } else {
          //查询收货地址中的默认收货地址，没有默认则使用第一条收货地址
          for (var i in addresslist) {
            if (addresslist[i]['Address_Is_Default'] == 1) {
              addressInfo = addresslist[i];
            }
          }
          if (!addressInfo || addressInfo.length <= 0) {
            addressInfo = addresslist[0];
          }
        }

        this.setData({
          back_address_id: 0,   //清空数据
          'address_info.Address_ID': addressInfo['Address_ID'],
          'address_info.Address_Name': addressInfo['Address_Name'],
          'address_info.Address_Mobile': addressInfo['Address_Mobile'],
          'address_info.Address_Province': area.area[0][0][addressInfo['Address_Province']],
          'address_info.Address_City': area.area[0][0 + ',' + addressInfo['Address_Province']][addressInfo['Address_City']],
          'address_info.Address_Area': area.area[0][0 + ',' + addressInfo['Address_Province'] + ',' + addressInfo['Address_City']][addressInfo['Address_Area']],
          'address_info.Address_Detailed': addressInfo['Address_Detailed']
        });
      }
    }
  },

  //提交地址
  formSubmit: function (e) {
    // //发送推送码    
    // utils.addMessageCode({
    //   users_id: app.globalData.init.users_id,
    //   userid: app.globalData.userInfo.id,
    //   code: e.detail.formId,
    //   times: 1
    // });
    // var info = e.detail.value;
    /**
     * 根据用户选择的发货方式判断需要写入的值 
     */
    var submit_info = {};
    if (!this.data.address_info.Address_ID && this.data.info.Gift_Shipping == 1) { //判断是否有收获地址
        wx.showModal({
          title: '提示',
          content: '请去添加收货地址',
          showCancel: false
        });
        return false;
      }
    // 必传参数: sign, timestamp, Biz_Account, User_ID, Gift_ID
    // 可选参数: Address_ID(当兑换的礼品需要物流时, 此参数为必传参数)
    var transData = {
      act: 'duihuan_pro',
      User_ID: app.globalData.userInfo.User_ID,
      Gift_ID: this.data.Gift_ID,
    }
    if (this.data.info.Gift_Shipping == 1){
      transData.AddressID = this.data.address_info.Address_ID
    }
    app.http_req(transData, app.globalData.init.api_url, 'POST', this.submit_callback);
  },
  //提交表单
  submit_callback: function (res) { 
    if (res.errorCode === 0) {
      wx.showToast({
        icon: 'cuccsss',
        title: "兑换成功",
        success:function(){
          wx.navigateTo({
            url: '../jifenorder/jifenorder',
          })
        }
    })
    }else{
      wx.showModal({
        title: '提示',
        content: res.msg,
        showCancel:false
      })
          
   }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  this.load()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },
})